package com.aqadoos.service;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.aqadoos.domain.User;

/**
 * User: Ata-ul.Qadoos
 */
@Component
@Scope("prototype")
@Transactional
public class UserService {
    
    @PersistenceContext
    private EntityManager em;
    
    public Long create(User user) {
        em.persist(user);
        return user.id;
    }
    
    public User findById(Long id) {
        return em.find(User.class, id);
    }
    
    public User findByUserId(String userId) {
        Query query = em.createQuery("from User u where u.userId=:userId");
        query.setParameter("userId", userId);
        @SuppressWarnings("unchecked")
		List<User> result = (List<User>) query.getResultList();
        if(result != null && result.size() > 0) {
            return result.get(0);
        }
        
        return null;
    }
    
    @SuppressWarnings("unchecked")
	public List<User> findAll() {
        Query query = em.createQuery("from User u");
        return (List<User>) query.getResultList();
    }
}
